package com.weiyi.chat.ui.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.easeui.widget.EaseSwitchButton;
import com.hyphenate.util.EMLog;
import com.weiyi.chat.MyApplication;
import com.weiyi.chat.R;
import com.weiyi.chat.common.Constant;
import com.weiyi.chat.common.DemoHelper;
import com.weiyi.chat.common.DemoModel;
import com.weiyi.chat.common.base.BaseActivity;
import com.weiyi.chat.utils.PreferenceUtil;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SettingActivity extends BaseActivity {

    @BindView(R.id.rl_mail_log)
    RelativeLayout mRlMailLog;
    @BindView(R.id.switch_notification)
    EaseSwitchButton mSwitchNotification;
    @BindView(R.id.rl_switch_notification)
    RelativeLayout mRlSwitchNotification;
    @BindView(R.id.textview1)
    TextView mTextview1;
    @BindView(R.id.switch_sound)
    EaseSwitchButton mSwitchSound;
    @BindView(R.id.rl_switch_sound)
    RelativeLayout mRlSwitchSound;
    @BindView(R.id.textview2)
    TextView mTextview2;
    @BindView(R.id.switch_vibrate)
    EaseSwitchButton mSwitchVibrate;
    @BindView(R.id.rl_switch_vibrate)
    RelativeLayout mRlSwitchVibrate;
    @BindView(R.id.rl_push_settings)
    RelativeLayout mRlPushSettings;
    @BindView(R.id.switch_speaker)
    EaseSwitchButton mSwitchSpeaker;
    @BindView(R.id.rl_switch_speaker)
    RelativeLayout mRlSwitchSpeaker;
    @BindView(R.id.ll_user_profile)
    LinearLayout mLlUserProfile;
    @BindView(R.id.ll_black_list)
    LinearLayout mLlBlackList;
    @BindView(R.id.textview4)
    TextView mTextview4;
    @BindView(R.id.switch_msg_roaming)
    EaseSwitchButton mSwitchMsgRoaming;
    @BindView(R.id.rl_msg_roaming)
    RelativeLayout mRlMsgRoaming;
    @BindView(R.id.btn_logout)
    Button mBtnLogout;
    private DemoModel settingsModel;
    private EMOptions chatOptions;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_setting;
    }

    @Override
    protected void initView() {
        settingsModel = DemoHelper.getInstance().getModel();
        chatOptions = EMClient.getInstance().getOptions();
    }

    @Override
    protected void initData() {
        // the vibrate and sound notification are allowed or not?
        if (settingsModel.getSettingMsgNotification()) {
            mSwitchNotification.openSwitch();
        } else {
            mSwitchNotification.closeSwitch();
        }

        // sound notification is switched on or not?
        if (settingsModel.getSettingMsgSound()) {
            mSwitchSound.openSwitch();
        } else {
            mSwitchSound.closeSwitch();
        }

        // vibrate notification is switched on or not?
        if (settingsModel.getSettingMsgVibrate()) {
            mSwitchVibrate.openSwitch();
        } else {
            mSwitchVibrate.closeSwitch();
        }

        // the speaker is switched on or not?
        if (settingsModel.getSettingMsgSpeaker()) {
            mSwitchSpeaker.openSwitch();
        } else {
            mSwitchSpeaker.closeSwitch();
        }

        if (settingsModel.isMsgRoaming()) {
            mSwitchMsgRoaming.openSwitch();
        } else {
            mSwitchMsgRoaming.closeSwitch();
        }

    }

    @OnClick({R.id.rl_mail_log, R.id.rl_switch_notification, R.id.rl_switch_sound, R.id.rl_switch_vibrate, R.id.rl_push_settings, R.id.rl_switch_speaker, R.id.ll_user_profile, R.id.ll_black_list, R.id.rl_msg_roaming, R.id.btn_logout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_mail_log:
                sendLogThroughMail();
                break;
            case R.id.rl_switch_notification:
                if (mSwitchNotification.isSwitchOpen()) {
                    mSwitchNotification.closeSwitch();
                    mRlSwitchSound.setVisibility(View.GONE);
                    mRlSwitchVibrate.setVisibility(View.GONE);
                    mTextview1.setVisibility(View.GONE);
                    mTextview2.setVisibility(View.GONE);
                    settingsModel.setSettingMsgNotification(false);
                } else {
                    mSwitchNotification.openSwitch();
                    mRlSwitchSound.setVisibility(View.VISIBLE);
                    mRlSwitchVibrate.setVisibility(View.VISIBLE);
                    mTextview1.setVisibility(View.VISIBLE);
                    mTextview2.setVisibility(View.VISIBLE);
                    settingsModel.setSettingMsgNotification(true);
                }
                break;
            case R.id.rl_switch_sound:
                if (mSwitchSound.isSwitchOpen()) {
                    mSwitchSound.closeSwitch();
                    settingsModel.setSettingMsgSound(false);
                } else {
                    mSwitchSound.openSwitch();
                    settingsModel.setSettingMsgSound(true);
                }
                break;
            case R.id.rl_switch_vibrate:
                if (mSwitchVibrate.isSwitchOpen()) {
                    mSwitchVibrate.closeSwitch();
                    settingsModel.setSettingMsgVibrate(false);
                } else {
                    mSwitchVibrate.openSwitch();
                    settingsModel.setSettingMsgVibrate(true);
                }
                break;
            case R.id.rl_push_settings:
                startActivity(new Intent(mAct, OfflinePushSettingsActivity.class));
                break;
            case R.id.rl_switch_speaker:
                if (mSwitchSpeaker.isSwitchOpen()) {
                    mSwitchSpeaker.closeSwitch();
                    settingsModel.setSettingMsgSpeaker(false);
                } else {
                    mSwitchSpeaker.openSwitch();
                    settingsModel.setSettingMsgVibrate(true);
                }
                break;
            case R.id.ll_user_profile:
                startActivity(new Intent(mAct, UserProfileActivity.class).putExtra("setting", true)
                        .putExtra("username", EMClient.getInstance().getCurrentUser()).putExtra("usernick", PreferenceUtil.getValue(Constant.SP_BUS_OWNER, mAct)));
                break;
            case R.id.ll_black_list:
                startActivity(new Intent(mAct, BlacklistActivity.class));
                break;
            case R.id.rl_msg_roaming:
                if (mSwitchMsgRoaming.isSwitchOpen()) {
                    mSwitchMsgRoaming.closeSwitch();
                    settingsModel.setMsgRoaming(false);
                } else {
                    mSwitchMsgRoaming.openSwitch();
                    settingsModel.setMsgRoaming(true);
                }
                break;
            case R.id.btn_logout:
                logout();
                break;
        }
    }

    void logout() {
        final ProgressDialog pd = new ProgressDialog(mAct);
        String st = getResources().getString(R.string.Are_logged_out);
        pd.setMessage(st);
        pd.setCanceledOnTouchOutside(false);
        pd.show();
        MyApplication.exitLogin();

        DemoHelper.getInstance().logout(true,new EMCallBack() {

            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    public void run() {
                        pd.dismiss();
                        // show login screen
//                        MainActivity.finish();
                        DemoHelper.getInstance().logout(false,null);
                        mAct.toLogin();
//                        startActivity(new Intent(mAct, LoginActivity.class));

                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        pd.dismiss();
                        Toast.makeText(mAct, "unbind devicetokens failed", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    void sendLogThroughMail() {
        String logPath = "";
        try {
            logPath = EMClient.getInstance().compressLogs();
        } catch (Exception e) {
            e.printStackTrace();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(mAct, "compress logs failed", Toast.LENGTH_LONG).show();
                }
            });
            return;
        }
        File f = new File(logPath);
        File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        if (f.exists() && f.canRead()) {
            try {
                storage.mkdirs();
                File temp = File.createTempFile("hyphenate", ".log.gz", storage);
                if (!temp.canWrite()) {
                    return;
                }
                boolean result = f.renameTo(temp);
                if (result == false) {
                    return;
                }
                Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
                intent.setData(Uri.parse("mailto:"));
                intent.putExtra(Intent.EXTRA_SUBJECT, "log");
                intent.putExtra(Intent.EXTRA_TEXT, "log in attachment: " + temp.getAbsolutePath());

                intent.setType("application/octet-stream");
                ArrayList<Uri> uris = new ArrayList<>();
                uris.add(Uri.fromFile(temp));
                intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,uris);
                startActivity(intent);
            } catch (final Exception e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mAct, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                    }
                });
            }
        }
    }

}
